package com.demo.auth.common.service;

import com.demo.common.redis.constants.CacheConstants;
import com.demo.common.core.exception.ServiceException;
import com.demo.common.redis.service.RedisService;
import com.demo.common.core.domain.SysUserBo;
import com.demo.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 登录密码方法
 *
 * @author demo
 */
@Component
public class SysPasswordService {
    @Autowired
    private RedisService redisService;

    private int maxRetryCount = CacheConstants.PASSWORD_MAX_RETRY_COUNT;

    private Long lockTime = CacheConstants.PASSWORD_LOCK_TIME;

    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param account 账号
     * @return 缓存键key
     */
    private String getCacheKey(String account) {
        return CacheConstants.PWD_ERR_CNT_KEY + account;
    }

    public void validate(SysUserBo user, String uk, String pk) {
        Integer retryCount = redisService.getCacheObject(getCacheKey(uk));
        if (retryCount == null) {
            retryCount = 0;
        }
        if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
            String errMsg = String.format("密码输入错误%s次，帐户锁定%s分钟", maxRetryCount, lockTime);
            throw new ServiceException(errMsg);
        }
        if (!matches(user, pk)) {
            retryCount = retryCount + 1;
            redisService.setCacheObject(getCacheKey(uk), retryCount, lockTime, TimeUnit.MINUTES);
            throw new ServiceException("账号或密码错误！");
        } else {
            clearLoginRecordCache(uk);
        }
    }

    public boolean matches(SysUserBo user, String rawPassword) {
        return SecurityUtils.matchesPassword(rawPassword, user.getPk());
    }

    public void clearLoginRecordCache(String loginName) {
        if (redisService.hasKey(getCacheKey(loginName))) {
            redisService.deleteObject(getCacheKey(loginName));
        }
    }
}
